#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :test.py
# @Time      :2024/3/21 
# @Author    :CL
# @email     :1037654919@qq.com
import os
import re
import shutil
import subprocess

import requests
from bs4 import BeautifulSoup

# 下载.m3u8链接中的音频文件
def download_m3u8_audio(folder_name,m3u8_url):
    # 下载.m3u8文件内容
    response = requests.get(m3u8_url)
    m3u8_content = response.text

    # 匹配所有的.ts文件链接并添加正确的schema
    base_url = '/'.join(m3u8_url.split('/')[:-1]) + '/'

    ts_urls = [base_url + line.strip() for line in m3u8_content.split('\n') if line.endswith('.ts')]
    print(ts_urls)

    # 下载每个.ts文件
    for index, ts_url in enumerate(ts_urls, start=1):
        response = requests.get(ts_url)
        file_path = os.path.join(folder_name, f"audio_{index}.ts")
        with open(file_path, 'wb') as f:
            f.write(response.content)

    print("音频文件下载完成")
# 合并所有的.ts文件为单个音频文件
def merge_ts_files(input_folder, output_file):
    ts_files = [f for f in os.listdir(input_folder) if f.endswith('.ts')]
    ts_files.sort()  # 按文件名排序，确保顺序正确
    file_list_path = os.path.join(input_folder, 'file_list.txt')

    # 将.ts文件列表写入文件
    with open(file_list_path, 'w') as f:
        for ts_file in ts_files:
            f.write(f"file '{ts_file}'\n")

    # 使用ffmpeg合并.ts文件为单个音频文件
    subprocess.run(['ffmpeg', '-f', 'concat', '-safe', '0', '-i', file_list_path, '-c:a', 'aac', '-b:a', '256k', '-y',
                    output_file])

    # 删除中间文件
    os.remove(file_list_path)

    # 删除保存.ts文件的文件夹
    shutil.rmtree(input_folder)

def down():
    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Pragma": "no-cache",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "none",
        "Sec-Fetch-User": "?1",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Linux\""
    }
    cookies = {
        "wdcid": "527af4fb80183ff4",
        "wdlast": "1704330276",
        "cna": "MvIcHr9qzCgCAXjo69I/84Ng"
    }
    url = "https://china.cnr.cn/gdgg/20240317/t20240317_526629919.shtml"
    response = requests.get(url, headers=headers, cookies=cookies)
    response.encoding = 'gb2312'
    print(response.url, response)

    soups = BeautifulSoup(response.text, 'html.parser')
    datas = soups.find('div', class_='article-content')

    HiRadioPlayers = datas.find_all('div', style='text-align:center')
    datas = soups.find('div', class_='article-content')

    div_tags = datas.find_all('div', style='text-align:center')
    texts_mapping = {}
    current_url = None
    name = ''
    for tag in datas.children:
        print(name)
        # print(tag)
        # 假设datas是您提供的BeautifulSoup对象中查找到的特定div节点
        if tag.name == 'p':
            print(tag.text)
            if name:
                texts_mapping[name].append(tag.text)
        elif tag.name == 'div' and tag.has_attr('style'):
            current_url = tag.find('div', class_='HiRadioPlayer')['data-url']
            # 假设current_url是包含音频文件的URL
            name = current_url.split('/')[-1].split('?')[0]
            if name.endswith('.m3u8'):
                # 读取m3u8文件内容
                # 下载.m3u8链接中的音频文件
                # 创建保存音频文件的文件夹
                folder_name = name.split('.m3u8')[0]
                # input_folder = os.path.join(os.getcwd(), folder_name)
                if not os.path.exists(folder_name):
                    os.makedirs(folder_name)

                download_m3u8_audio(folder_name, current_url)
                # 如果需要，可以将.ts文件合并为单个音频文件
                merge_ts_files(input_folder=folder_name, output_file=name.replace('.m3u8', '.mp4'))
                #

            else:
                response = requests.get(current_url)
                if response.status_code == 200:
                    # 提取音频文件名
                    file_name = current_url.split('/')[-1]

                    # 写入音频文件
                    with open(name, 'wb') as file:
                        file.write(response.content)

            print(f'Current URL: {current_url}, Name: {name}')
            texts_mapping[name] = []

    for name, texts in texts_mapping.items():
        print(name, texts)
        txt_name = name.split('.')[0] + '.txt'
        with open(txt_name, "w", encoding="utf-8") as file:
            file.write("\n".join(texts))


if __name__ ==    "__main__":
    print()
    # down()